<!DOCTYPE html>
<html>

<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width,initial-scale=1">
	<title>本地 ip 地址查询</title>
	<script src="./wasm_exec.js"></script>
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/xmdhs/searchqanda/style.css">
	<script>
		if (window.fetch == null || window.WebAssembly == null) {
			window.onload = function () {
				document.getElementById("ipInfo").innerHTML = "请更新浏览器，<a href=\"https://www.google.cn/intl/zh-CN/chrome/\">https://www.google.cn/intl/zh-CN/chrome/</a>";
			}
		}
	</script>
	<script>
		async function getDb() {
			let f = await fetch("https://cdn.jsdelivr.net/gh/lionsoul2014/ip2region/data/ip2region.db")
			if (f.status != 200) {
				throw new Error(f.statusText)
			}
			let b = await f.arrayBuffer()
			return new Uint8Array(b);
		}
		let go;
		try {
			go = new Go();
		} catch (error) {
			window.onload = function () {
				document.getElementById("ipInfo").innerHTML = "请更新浏览器，<a href=\"https://www.google.cn/intl/zh-CN/chrome/\">https://www.google.cn/intl/zh-CN/chrome/</a>";
			}
		}
		async function fetchAndInstantiate() {
			const response = await fetch("./ip.wasm");
			const buffer = await response.arrayBuffer();
			const obj = await WebAssembly.instantiate(buffer, go.importObject)
			go.run(obj.instance);
			let b;
			try {
				b = await getDb();
			} catch (error) {
				document.getElementById("ipInfo").innerText = "获取 ip 数据库失败\n" + error;
				console.warn(error);
				return;
			}
			setDB(b);
			document.getElementById('ip').removeAttribute("readOnly");
			document.getElementById("ipInfo").innerText = "";
		}
		fetchAndInstantiate();
		function Form() {
			let ip = document.querySelector("#ip").value.toString();
			if (ip == "") {
				return;
			}
			getIp(ip, (v) => {
				let s = v.Country + v.Province + v.City + v.ISP
				s = s.replace(/0/g, "")
				document.getElementById("ipInfo").innerText = s;
			})
			return false;
		}
		window.addEventListener("load", () => {
			let f = document.getElementById("getip");
			f.addEventListener("submit", function (event) {
				event.preventDefault();
				Form();
			});
		})
	</script>
</head>

<body>
	<div class="container-lg px-3 my-5 markdown-body">
		<h1>本地 ip 地址查询</h1>
		<form id="getip">
			<input type="search" id="ip" placeholder="1.1.1.1" name="ip" readonly="readonly" title="ipv4"
				pattern="^((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}$">
			<input type="submit" value="查询">
		</form>
		<br>
		<div id="ipInfo">加载 ip 数据库中...</div>
		<hr>
		<details>
			<summary>说明</summary>
			<p>所有查询均在本地进行，不会发送任何请求到其他地方。</p>
			<p>数据库来自 <a href="https://github.com/lionsoul2014/ip2region">https://github.com/lionsoul2014/ip2region</a>
			</p>
		</details>
	</div>
</body>

</html>